import {Message} from 'element-ui'

//工具包

//正则匹配
//匹配帐号
const regUid = function (str) {
    return !RegExp(/^\w{6,12}$/).test(str);
}

const regName = function(str){
	return !RegExp(/^[\u4e00-\u9fa5]{2,5}$/).test(str);
}

//匹配身份证
const regIDC = function (str) {
     return !RegExp(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/).test(str);
}
//匹配手机号
const regPhone = function (str) {
     return !RegExp(/^1[345789]\d{9}$/).test(str);
}
//匹配验证码
const regCheckNum = function (str) {
    return !RegExp(/^\d{4}$/).test(str);
}

//匹配邮箱格式
const regEmail = function (str){
	return !RegExp(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/).test(str);
}
//判断对象是否为空
const object_dede=function (params) {
  let flag = true;
 
  for(var key in params){
    if(params[key] != '0' && !params[key]){
      Message.warning("错了哦，这是一条错误消息");
      return false; // 终止程序
    }
  }
 
  return flag;
}


//接受一个id 返回祖先所有id
 const findAncestors = (tree, nodeId) => {
  function findAncestorsRecursive(node, nodeId, ancestors) {
    if (!node) {
      return null;
    }

    ancestors.push(node.id);

    if (node.id === nodeId) {
      // 找到目标节点，返回祖先数组
      return ancestors;
    }

    // 递归查找父节点
    for (const child of node.children || []) {
      const result = findAncestorsRecursive(child, nodeId, ancestors.slice());
      if (result) {
        return result;
      }
    }

    return null;
  }

  // 从根节点开始查找
  for (const root of tree) {
    const ancestors = findAncestorsRecursive(root, nodeId, []);
    if (ancestors) {
      return ancestors; // 将结果反转，得到从根节点到目标节点的顺序
    }
  }

  return null; // 如果找不到目标节点，返回 null 或者其他适当的值
};
//数组转树结构
 const listToTree = (data, findKey) => {
  let arr = JSON.parse(JSON.stringify(data));
  const listChildren = (obj, filter) => {
    [arr, obj.children] = arr.reduce(
      (res, val) => {
        val.topic = val.name;
        if (filter(val)) {
          res[1].push(val);
        } else {
          res[0].push(val);
        }
        return res;
      },
      [[], []]
    );
    obj.children.forEach((val) => {
      if (arr.length) {
        listChildren(val, (obj) => obj.parentId == val[findKey || "id"]);
      }
    });
    // if (!obj.children.length) {
    //     delete obj.children;
    // }
  };
  const tree = {};
  listChildren(
    tree,
    (val) => arr.findIndex((i) => i[findKey || "id"] == val.parentId) == -1
  );
  return tree.children;
};
export default{
    regUid,
    regName,
    regIDC,
    regPhone,
    regCheckNum,
    regEmail,
    object_dede,
    findAncestors,
    listToTree
}